package code.zzl.monitor.sdk.appender;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import cn.hutool.core.util.ArrayUtil;
import code.zzl.monitor.sdk.model.LogMessage;
import code.zzl.monitor.sdk.push.IPush;
import code.zzl.monitor.sdk.push.impl.RedisPush;
import lombok.Data;

import java.util.Arrays;

/**
 * @ Author 龙
 * @ Date 2024-07-31 12:43
 * @ Description: 自定义日志采集
 */
@Data
public class CustomAppender<E> extends AppenderBase<E> {

    // 系统名称
    private String systemName;
    // 只采集指定范围的日志
    private String groupId;
    // redis 连接地址
    private String host;
    // redis 连接端口
    private Integer port;
    // redis 连接密码
    private String password;

    private final IPush push = new RedisPush();

    @Override
    protected void append(E eventObject) {
        //建立连接
        push.open(host, port, password);
        String methodName = "unknown";
        String className = "unknown";
        if (eventObject instanceof ILoggingEvent){
            ILoggingEvent event = (ILoggingEvent) eventObject;
            StackTraceElement[] callerDataArray = event.getCallerData();
            if (!ArrayUtil.isEmpty(callerDataArray)){
                StackTraceElement callerData = callerDataArray[0];
                methodName = callerData.getMethodName();
                className = callerData.getClassName();
            }
            if (!className.startsWith(groupId)){
                return;
            }
            //构建消息
            LogMessage logMessage = LogMessage.builder()
                            .systemName(systemName)
                            .methodName(methodName)
                            .className(className)
                            .logList(Arrays.asList(event.getFormattedMessage().split(" ")))
                            .build();
            System.out.println("构建完的消息: " + logMessage);
            push.send(logMessage);

        }

    }
}
